package com.hsmedia.mlkitdemo

import android.Manifest
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.PermissionChecker
import com.mhy.mlkit.ScanningActivity
import com.mhy.mlkit.ScanningActivity.Companion.SCAN_RESULT
import com.mhy.mlkit.Utils

/*
StartActivityForResult()
StartIntentSenderForResult()
RequestMultiplePermissions()
RequestPermission()
TakePicturePreview()
TakePicture()
TakeVideo()
PickContact()
GetContent()
GetMultipleContents()
OpenDocument()
OpenMultipleDocuments()
OpenDocumentTree()
CreateDocument()
 */
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        // 想要图片沉浸, 必须设置fitsSystemWindows=false
        Utils.setRootViewFitsSystemWindows(this, false)
        //设置状态栏透明
        Utils.setTranslucentStatus(this)
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!Utils.setStatusBarDarkTheme(this, false)) {
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            Utils.setStatusBarColor(this, 0x55000000)
        }
    }

    private val requestDataLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val data = result.data?.getStringExtra(SCAN_RESULT)
                findViewById<TextView>(R.id.tv_result).text = data
            }
        }
    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
            if (granted) {
                // User allow the permission.
                scan(null)
            } else {
                // User deny the permission.
            }
        }

    fun scan(view: android.view.View?) {
        if (PermissionChecker.checkSelfPermission(this, Manifest.permission.CAMERA) ==
            PermissionChecker.PERMISSION_GRANTED) {
            val intent = Intent(this, ScanningActivity::class.java)
            requestDataLauncher.launch(intent)
        } else {
            requestPermissionLauncher.launch(Manifest.permission.CAMERA)
        }
    }
}